package com.qf.thread.compalate;

import java.net.HttpRetryException;
import java.util.concurrent.*;
import java.util.function.Supplier;

public class RunAsyncDemo {

    public static void main(String[] args) throws ExecutionException, InterruptedException {


        // 创建一个线程池
        ThreadPoolExecutor executor = new ThreadPoolExecutor(
                5,
                20,
                2000,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<Runnable>(10000),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy()
        );

//        CompletableFuture.runAsync(new Runnable() {
//            @Override
//            public void run() {
//                System.out.println("一个线程运行了");
//            }
//        });


        // 启动一个去执行 runAsync()这个方法是没有返回值的
        CompletableFuture.runAsync(() -> {
            System.out.println("一个线程运行了:" + Thread.currentThread().getName());
        });

        // 从线程池中申请一个先从去执行
        CompletableFuture<Void> voidCompletableFuture = CompletableFuture.runAsync(() -> {
            System.out.println("从线程池中去申请一个线程执行的:" + Thread.currentThread().getName());
        }, executor);


        // 从线程池中申请一个线程去执行，这个线程是有返回值的
//        CompletableFuture<String> future = CompletableFuture.supplyAsync(new Supplier<String>() {
//            @Override
//            public String get() {
//                int sum = 0;
//                for (int i = 0; i < 10; i++) {
//                    sum += i;
//                    try {
//                        Thread.sleep(200);
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    }
//                }
//                return "sum:" + sum;
//            }
//        }, executor);

        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            int sum = 0;
            for (int i = 0; i < 10; i++) {
                sum += i;
                try {
                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            return "sum:" + sum;
        }, executor);

        // 获取线程的计算结果
        String s = future.get(); // 这个方法是阻塞方法
        System.out.println("main:" + s);

//        executor.shutdown();
//        System.out.println("线程池关闭了。。。。");
    }
}
